package cn.micro.eye.commons.oss;

import cn.micro.eye.commons.trace.Trace;
import com.qiniu.common.Zone;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * Qi Niu Oss Service
 *
 * @author lry
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(QiNiuOssProperties.class)
@ConditionalOnProperty(prefix = "micro.oss.qi-niu", name = "enable", havingValue = "true")
public class QiNiuOssService {

    @Resource
    private QiNiuOssProperties properties;

    @Resource
    private Auth qiNuiAuth;
    @Resource
    private UploadManager qiNiuUploadManager;

    @Bean
    public Auth qiNuiAuth() {
        return Auth.create(properties.getAccessKey(), properties.getSecretKey());
    }

    @Bean
    public UploadManager qiNiuUploadManager() {
        com.qiniu.storage.Configuration cfg = new com.qiniu.storage.Configuration();
        cfg.zone = Zone.zone0();
        cfg.retryMax = properties.getRetryMax();
        cfg.putThreshold = properties.getPutThreshold();
        cfg.readTimeout = properties.getReadTimeoutSec();
        cfg.writeTimeout = properties.getWriteTimeoutSec();
        cfg.connectTimeout = properties.getConnectTimeoutSec();
        return new UploadManager(cfg);
    }

    @Trace
    public String getUploadToken() {
        return qiNuiAuth.uploadToken(properties.getBucket(),
                null, properties.getTokenExpiresSec(), null, true);
    }

    public String getAccessUrl() {
        return properties.getAccessUrl();
    }

}
